

from PyQt5 import QtCore, QtGui, QtWidgets
import component.voice_recorder.audiorecorder as au
import component.voice_recorder.utils as utils
import component.voice_recorder.audiolevel as audiolevel

class RecorderWidget(QtWidgets.QWidget):
    def __init__(self):
        super(RecorderWidget, self).__init__()

        #设置recoder
        self._audio_recorder = au.AudioRecorder(self)
        # 音量监听器
        self._level_monitors = [
            audiolevel.AudioLevelMonitor(self),
            audiolevel.AudioLevelMonitor(self),
        ]

        # 音量计算绑定更新事件
        self._audio_levels_calculator = audiolevel.AudioLevelsCalculator(self, self._audio_recorder.recorder)
        self._audio_levels_calculator.levels_calculated.connect(self._on_show_audio_levels)

        self.setupUI()

    def setRecordTitle(self,title):
        self._audio_recorder.setTitle(title)

    def setupUI(self):

        self.gridLayout_4 = QtWidgets.QGridLayout(self)
        self.gridLayout_4.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_4.setObjectName("gridLayout_5")

        self.frame_7 = QtWidgets.QFrame()
        self.frame_7.setMaximumSize(QtCore.QSize(16777215, 48))
        self.frame_7.setStyleSheet("#frame_7{\n"
                                   "background-color:#FAFAFA;\n"
                                   "    border-radius:15px\n"
                                   "}")
        self.frame_7.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_7.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_7.setObjectName("frame_7")
        self.gridLayout_4.addWidget(self.frame_7,0,0)

        self.gridLayout_2 = QtWidgets.QGridLayout(self.frame_7)
        self.gridLayout_2.setContentsMargins(-1, 10, -1, 10)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.start_stop_record = QtWidgets.QPushButton(self.frame_7)
        self.start_stop_record.setMinimumSize(QtCore.QSize(0, 30))
        self.start_stop_record.setMaximumSize(QtCore.QSize(130, 40))
        self.start_stop_record.setCheckable(True)
        self.start_stop_record.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.start_stop_record.setStyleSheet("#start_stop_record{\n"
"    background-color:transparent;\n"
"    border-radius:10px;\n"
"border-color:white;\n"
"margin-left:5px;\n"
"color:black;\n"
"}")
        icon5 = QtGui.QIcon()
        icon5.addPixmap(QtGui.QPixmap("./imgs/record1.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.start_stop_record.setIcon(icon5)
        self.start_stop_record.setIconSize(QtCore.QSize(20, 20))
        self.start_stop_record.setObjectName("start_stop_record")
        self.gridLayout_2.addWidget(self.start_stop_record, 0, 0, 1, 1)

        self.labelRecordDuration = QtWidgets.QLabel(self.frame_7)
        self.labelRecordDuration.setObjectName("labelRecordDuration")
        self.gridLayout_2.addWidget(self.labelRecordDuration, 0, 1, 1, 1)

        # 音量显示组件
        self.layoutAudioLevels = QtWidgets.QVBoxLayout()
        self.layoutAudioLevels.setSpacing(2)
        self.layoutAudioLevels.setObjectName("layoutAudioLevels")
        self.gridLayout_2.addLayout(self.layoutAudioLevels, 0, 2, 1, 1)

        for levmon in self._level_monitors:
            levmon.setVisible(False)
            levmon.setMinimumWidth(50)
            levmon.setMaximumWidth(250)
            levmon.setFrameStyle(QtWidgets.QFrame.StyledPanel)

            self.layoutAudioLevels.addWidget(levmon)

        spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.gridLayout_2.addItem(spacerItem2, 0, 3, 1, 1)

        self.start_stop_record.setText("开始录制")

        self.setupEvent()

    def setupEvent(self):

        self._audio_recorder.recording_progress.connect(self._on_update_duration_time)
        self.start_stop_record.toggled.connect(self._on_start_stop)


    def _on_start_stop(self, is_checked):
        pb_title_text = {
            True: self.tr('停止录制'),
            False: self.tr('回答已录制'),
        }

        self.start_stop_record.setText(pb_title_text[is_checked])
        # 显示音量组件
        for levmon in self._level_monitors:
            levmon.setVisible(is_checked)

        if is_checked:
            icon5 = QtGui.QIcon()
            icon5.addPixmap(QtGui.QPixmap("./imgs/end_record.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.start_stop_record.setIcon(icon5)
            self.start_stop_record.setIconSize(QtCore.QSize(20, 20))
        else:

            icon5 = QtGui.QIcon()
            icon5.addPixmap(QtGui.QPixmap("./imgs/finish_record.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.start_stop_record.setIcon(icon5)
            self.start_stop_record.setIconSize(QtCore.QSize(20, 20))
            self.start_stop_record.setCheckable(False)
            self.start_stop_record.setStyleSheet("#start_stop_record{\n"
                                             "    background-color:transparent;\n"
                                             "    border-radius:10px;\n"
                                             "border-color:white;\n"
                                             "margin-left:5px;\n"
                                             "margin-right:30px;\n"
                                             "color:#707070;\n"
                                             "}")
            self.frame_7.setStyleSheet("#frame_7{\n"
                                       "background-color:#f1ffff;\n"
                                       "    border-radius:15px;\n"
                                       "}")


        if is_checked:
            self._start_recording()
        else:
            self._stop_recording()

    def _start_recording(self):
        #开始录制
        self._audio_recorder.start()
        # 设置录制时间为0
        self._on_update_duration_time(0)
        # self._recording_status_info.set_record_status()

        # self.ui.pbRecordingStartAndStop.setIcon(QtGui.QIcon(':icons/stop'))

    def _stop_recording(self):
        QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))

        try:
            self._audio_recorder.stop()
        except Exception as err:
            QtWidgets.QMessageBox.critical(self, 'Unable to save record', f'{err}')
        finally:
            QtWidgets.QApplication.restoreOverrideCursor()


    # 更新录制时间
    def _on_update_duration_time(self, duration):
        self.labelRecordDuration.setText(utils.format_duration(duration))

    def _on_show_audio_levels(self, levels: list):
        for mon, level in zip(self._level_monitors, levels):
            mon.set_level(level)

